<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>贪吃蛇</title>
	</head>
	<body>
		<canvas id="gc" width="400" height="400"></canvas>
		<script type="text/javascript">
			var csnv,ctx;
			window.onload = function(){
				canv = document.getElementById("gc");
				ctx = canv.getContext("2d");
				document.addEventListener("keydown",keyPush);//addEventListener() 方法用于向指定元素添加事件句柄。
				setInterval(game,1000/5);
			}
			var px = 10,py = 10;//蛇起始位置
			var gs = 20,tc = 20;//画布分成20份
			var ax = 15,ay = 15;//苹果位置
			var xv = 0,yv = 0;
			var trail = [];
			var tail = 5;
			function game(){
				px += xv;
				py += yv;
				if(px < 0){
					px = tc - 1;
				}
				if(px > tc - 1){
					px = 0;
				}
				if(py < 0){
					py = tc - 1;
				}
				if(py > tc - 1){
					py = 0;
				}
				ctx.fillStyle = "black";
				ctx.fillRect(0, 0, canv.width, canv.height);
				
				ctx.fillStyle = "lime";
				for(var i = 0; i < trail.length; i ++){
					ctx.fillRect(trail[i].x*gs, trail[i].y*gs, gs-2, gs-2);
					if(trail[i].x == px && trail[i].y == py){
						tail = 5;
					}
				}
				trail.push({x:px,y:py});
				while(trail.length > tail){
					trail.shift();
				}
				
				if(ax == px && ay == py){
					tail ++;
					ax = Math.floor(Math.random()*tc);
					ay = Math.floor(Math.random()*tc);
				}
				
				ctx.fillStyle = "red";
				ctx.fillRect(ax*gs, ay*gs, gs-2, gs-2);
			}
			function keyPush(evt){
				switch(evt.keyCode){
					case 37://左
					xv = -1;yv = 0;
					break;
					case 38://上
					xv = 0;yv = -1;
					break;
					case 39://右
					xv = 1;yv = 0;
					break;
					case 40://下
					xv = 0;yv = 1;
					break;
				}
			}
		</script>
	</body>
</html>
